<?php

define('check', true);

session_start();

$redirect_uri = $_SESSION['redirect_uri'];

if (empty($redirect_uri)) {
    return;
}
$redirect_uri = urldecode($redirect_uri);
$code = $_GET['code'];

if (empty($code)) {
    return;
}

require_once './config.php';
$appid = appid;
$secret = secret;
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';


$res = geturl($url);
if (!isset($res['openid'])) {
    return;
}

$symbol = '?';
if (strpos($redirect_uri, '?')) {
    $symbol = '&';
}



//获得openid
$openid = $res['openid'];

if (getInfo === false) {

    //携带openid返回
    $redirect_uri = $redirect_uri . $symbol . 'openid=' . $openid;
    //跳转回去
    header("Location: {$redirect_uri}");
    die();
}

//获取access_token
$access_token = $res['access_token'];
//获取微信信息
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';

$res = geturl($url);
//将微信信息返回去
header("Location: {$redirect_uri}{$symbol}info=" . base64_encode(json_encode($res)));

function geturl($url)
{
    $headerArray = array("Content-type:application/json;", "Accept:application/json");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    $output = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($output, true);
    return $output;
}
